package com.hw.one.dam2.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.hw.one.dam2.util.UserSiteUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hw.one.dam2.common.SiteTypeEnum;
import com.hw.one.dam2.dao.IRegionSiteDao;
import com.hw.one.dam2.dao.IWaterPollutionDao;
import com.hw.one.dam2.entity.PollutionIndustryEntity;
import com.hw.one.dam2.param.PollutionIndustryParam;
import com.hw.one.dam2.param.RegionSiteParam;
import com.hw.one.ext.util.UserUtil;
import com.hw.one.util.DateTimeUtil;
import org.springframework.util.StringUtils;

@Service(value = "waterPollutionService")
public class WaterPollutionService implements IWaterPollutionService {

    @Autowired
    private IWaterPollutionDao waterPollutionDao;

    @Autowired
    private IRegionSiteDao regionSiteDao;

    @SuppressWarnings("rawtypes")
    @Override
    public List<Map> findWaterPollutionNewHourDataByPSCodeAndOutputCodes(List<String> siteCodeList) throws Exception {
        return waterPollutionDao.findWaterPollutionNewHourDataByPSCodeAndOutputCodes(siteCodeList);
    }

    @Override
    public List<PollutionIndustryEntity> findWaterPollutionDataByPSCode(HttpServletRequest request) throws Exception {
        // 判断用户是否具有访问权限
        if (!UserSiteUtil.userIsNotContainSiteTypes("201")) {
            return new ArrayList<PollutionIndustryEntity>();
        }
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        Calendar calendar = Calendar.getInstance();

        if (null == endTime || "".equals(endTime)) {
            endTime = DateTimeUtil.getFormatDateStr(calendar.getTime(), "yyyy-MM-dd HH:00:00");
        }

        if (null == startTime || "".equals(startTime)) {
            // 近两天的数据
            calendar.add(Calendar.DAY_OF_MONTH, -2);
            startTime = DateTimeUtil.getFormatDateStr(calendar.getTime(), "yyyy-MM-dd HH:00:00");
        }
        // 数据类型：小时数据hourData;日数据 dayData
        String dataType = request.getParameter("dataType");
        dataType = null == dataType || "".equals(dataType) ? "hourData" : dataType;

        Map<String, Object> region = UserUtil.getRegion();
        String userRegionCode = (String) region.get("regionCode");
        String userRegionType = (String) region.get("regionType");

        /**
         * 根据当前登录用户区域，查询该区域的上级区域
         *
         * 如果是区（regionType为22）县（regionType为24）需要查找上级区域，直属市
         *
         */
        if (20 <= Integer.parseInt(userRegionType)) {
            List<Map<String, Object>> parentRegionList = regionSiteDao.findParentRegionInfoByRegionCode(userRegionCode);
            // 把登录用户所属省份、和市编码，读取出来
            for (Map<String, Object> parentRegionMap : parentRegionList) {
                String retionType = String.valueOf(parentRegionMap.get("regionType"));
                // 市级名称
                if ("20".equals(retionType)) {
                    userRegionCode = String.valueOf(parentRegionMap.get("regionCode"));
                    break;
                }
            }
        }
        // 查询城市和企业名称
        String searchRegionCode = request.getParameter("regionCode");
        String searchCompanyName = request.getParameter("companyName");
        String siteCodes = request.getParameter("siteCodes");
        // 查询点位信息的参数Map
        RegionSiteParam paraSiteMap = new RegionSiteParam();
        paraSiteMap.setRegionCode(userRegionCode);
        if (null != searchRegionCode) {
            paraSiteMap.setRegionCode(searchRegionCode);
        }
        paraSiteMap.setCompanyName(searchCompanyName);
        if (null != siteCodes && !"".equals(siteCodes)) {
            List<String> siteCodeList = new ArrayList<>();
            Collections.addAll(siteCodeList, siteCodes.split(","));
            paraSiteMap.setSiteCodeList(siteCodeList);
        }
        paraSiteMap.setSiteType(SiteTypeEnum.WATER_POLLUTION_SITE.getValue());


        // 点位信息列表
        List<Map<String, Object>> siteInfoList = regionSiteDao.findSiteInfoByRegionCodeAndSiteType(paraSiteMap);

        if (siteInfoList == null || siteInfoList.size() == 0) {
            return new ArrayList<PollutionIndustryEntity>();
        }
        // 点位编码列
        List<String> pointCodeList = new ArrayList<String>();
        for (Map<String, Object> siteMap : siteInfoList) {
            pointCodeList.add(String.valueOf(siteMap.get("siteCode")));
        }

        PollutionIndustryParam paramPO = new PollutionIndustryParam();
        paramPO.setPSCodeList(pointCodeList);
        paramPO.setStartTime(startTime);
        paramPO.setEndTime(endTime);

        // 默认读取 工业废水 小时数据
        String collectionName = "T_DATA_WATERPOLLUTION_HOUR_S_COLLECT";

        // 如果是日数据
        if ("dayData".equals(dataType)) {
            collectionName = "T_DATA_WATERPOLLUTION_DAY_S_COLLECT";
        }

        // 根据条件查询相应数据
        List<PollutionIndustryEntity> waterDataList = waterPollutionDao.findWaterPollutionDataByPSCode(paramPO, collectionName);

        int sortIndex = 1;

        for (PollutionIndustryEntity ipPo : waterDataList) {
            // 排序
            ipPo.setIndex(String.valueOf(sortIndex++));

            String monitorTime = ipPo.getMonitorTime();

            if (monitorTime != null && !"".equals(monitorTime)) {
                if ("dayData".equals(dataType)) {
                    ipPo.setMonitorTime(monitorTime.substring(0, 10));
                } else {
                    ipPo.setMonitorTime(monitorTime.substring(0, 16));
                }
            }

            // 点位编码
            String dataPSCode = ipPo.getPSCode();

            // 点位信息列表
            for (Map<String, Object> siteMap : siteInfoList) {
                String siteCode = (String) siteMap.get("siteCode");

                // 把点位名称 区域名称设置好
                if (siteCode.equals(dataPSCode)) {
                    String siteName = String.valueOf(siteMap.get("siteName"));
                    String cityName = String.valueOf(siteMap.get("RegionName"));

                    ipPo.setCompanyName(siteName);
                    ipPo.setCityName(cityName);

                    break;
                }
            }
            setWaterData(ipPo);
        }

        return waterDataList;
    }

    @Override
    public List<PollutionIndustryEntity> findWaterPollutionLast12HourDataBySiteCode(String siteCode) {
        return waterPollutionDao.findWaterPollutionLast12HourDataBySiteCode(siteCode);
    }


    private void setWaterData(PollutionIndustryEntity industryEntity) {
        if (industryEntity == null) {
            return;
        }
        if (StringUtils.isEmpty(industryEntity.getPFL001()) || "0".equals(industryEntity.getPFL001()) || "0.0".equals(industryEntity.getPFL001())) {
            industryEntity.setPFL001("-");
        }

        if (StringUtils.isEmpty(industryEntity.getPFL002()) || "0".equals(industryEntity.getPFL002()) || "0.0".equals(industryEntity.getPFL002())) {
            industryEntity.setPFL002("-");
        }

        if (StringUtils.isEmpty(industryEntity.getPFL003()) || "0".equals(industryEntity.getPFL003()) || "0.0".equals(industryEntity.getPFL003())) {
            industryEntity.setPFL003("-");
        }

        if (StringUtils.isEmpty(industryEntity.getAvgStrength001()) || "0".equals(industryEntity.getAvgStrength001()) || "0.0".equals(industryEntity.getAvgStrength001())) {
            industryEntity.setAvgStrength001("-");
        }

        if (StringUtils.isEmpty(industryEntity.getAvgStrength002()) || "0".equals(industryEntity.getAvgStrength002()) || "0.0".equals(industryEntity.getAvgStrength002())) {
            industryEntity.setAvgStrength002("-");
        }

        if (StringUtils.isEmpty(industryEntity.getAvgStrength003()) || "0".equals(industryEntity.getAvgStrength003()) || "0.0".equals(industryEntity.getAvgStrength003())) {
            industryEntity.setAvgStrength003("-");
        }

        if (StringUtils.isEmpty(industryEntity.getAvgZsStrength001()) || "0".equals(industryEntity.getAvgZsStrength001()) || "0.0".equals(industryEntity.getAvgZsStrength001())) {
            industryEntity.setAvgZsStrength001("-");
        }

        if (StringUtils.isEmpty(industryEntity.getAvgZsStrength002()) || "0".equals(industryEntity.getAvgZsStrength002()) || "0.0".equals(industryEntity.getAvgZsStrength002())) {
            industryEntity.setAvgZsStrength002("-");
        }

        if (StringUtils.isEmpty(industryEntity.getAvgZsStrength003()) || "0".equals(industryEntity.getAvgZsStrength003()) || "0.0".equals(industryEntity.getAvgZsStrength003())) {
            industryEntity.setAvgZsStrength003("-");
        }

    }

}
